<?php

namespace App\Http\Controllers\Admin\Finance\Payable;

use App\Http\Controllers\Controller;
use App\Models\finance\PayableTradeModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class Trade extends Controller
{
    /**
     * 一般贸易列表
     */
    public function list(Request $request)
    {
        $date_start = $request->input('date_start', '');
        $date_end = $request->input('date_end', '');
        $plate_number = $request->input('plate_number', '');
        $loading_location = $request->input('loading_location', '');
        $unloading_location = $request->input('unloading_location', '');
        $agent_id = $request->input('agent_id', '');
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);

        $query = PayableTradeModel::with(['createAdmin']);

        if ($date_start && $date_end) {
            $query->whereBetween('date', [$date_start, $date_end]);
        }

        if ($plate_number) {
            $query->where('plate_number', 'like', "%{$plate_number}%");
        }

        if ($loading_location) {
            $query->where('loading_location', 'like', "%{$loading_location}%");
        }

        if ($unloading_location) {
            $query->where('unloading_location', 'like', "%{$unloading_location}%");
        }

        if ($agent_id) {
            $query->where('agent_id', $agent_id);
        }

        $total = $query->count();
        $items = $query->orderBy('id', 'desc')
            ->offset(($page - 1) * $limit)
            ->limit($limit)
            ->get()
            ->map(function($item) {
                return [
                    'id' => $item->id,
                    'agent_id' => $item->agent_id,
                    'agent_name' => $item->agent->name ?? '',
                    'date' => $item->date,
                    'mode' => $item->mode,
                    'plate_number' => $item->plate_number,
                    'tonnage' => $item->tonnage,
                    'loading_location' => $item->loading_location,
                    'customs_location' => $item->customs_location,
                    'unloading_location' => $item->unloading_location,
                    'freight_rmb' => $item->freight_rmb,
                    'mainland_addition_rmb' => $item->mainland_addition_rmb,
                    'overtime_rmb' => $item->overtime_rmb,
                    'no_wait_rmb' => $item->no_wait_rmb,
                    'parking_fee_rmb' => $item->parking_fee_rmb,
                    'weighing_fee_rmb' => $item->weighing_fee_rmb,
                    'registration_fee_hkd' => $item->registration_fee_hkd,
                    'parking_fee_hkd' => $item->parking_fee_hkd,
                    'other_hkd' => $item->other_hkd,
                    'total_cost_rmb' => $item->total_cost_rmb,
                    'remarks' => $item->remarks,
                ];
            });

        return $this->success([
            'list' => $items,
            'total' => $total,
        ]);
    }

    /**
     * 添加一般贸易记录
     */
    public function add(Request $request)
    {
        $params = $request->all();
        $validator = Validator::make($params, [
            'date' => 'required|date',
            'mode' => 'required|string',
            'plate_number' => 'required|string',
            'tonnage' => 'required|numeric|min:0',
            'loading_location' => 'required|string',
            'customs_location' => 'required|string',
            'unloading_location' => 'required|string',
            'freight_rmb' => 'required|numeric|min:0',
            'mainland_addition_rmb' => 'required|numeric|min:0',
            'overtime_rmb' => 'required|numeric|min:0',
            'no_wait_rmb' => 'required|numeric|min:0',
            'parking_fee_rmb' => 'required|numeric|min:0',
            'weighing_fee_rmb' => 'required|numeric|min:0',
            'registration_fee_hkd' => 'required|numeric|min:0',
            'parking_fee_hkd' => 'required|numeric|min:0',
            'other_hkd' => 'required|numeric|min:0',
            'total_cost_rmb' => 'required|numeric|min:0',
            'agent_id' => 'required|integer|min:1',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        try {
            $trade = new PayableTradeModel();
            $trade->date = $params['date'];
            $trade->mode = $params['mode'];
            $trade->plate_number = $params['plate_number'];
            $trade->tonnage = $params['tonnage'];
            $trade->loading_location = $params['loading_location'];
            $trade->customs_location = $params['customs_location'];
            $trade->unloading_location = $params['unloading_location'];
            $trade->freight_rmb = $params['freight_rmb'];
            $trade->mainland_addition_rmb = $params['mainland_addition_rmb'];
            $trade->overtime_rmb = $params['overtime_rmb'];
            $trade->no_wait_rmb = $params['no_wait_rmb'];
            $trade->parking_fee_rmb = $params['parking_fee_rmb'];
            $trade->weighing_fee_rmb = $params['weighing_fee_rmb'];
            $trade->registration_fee_hkd = $params['registration_fee_hkd'];
            $trade->parking_fee_hkd = $params['parking_fee_hkd'];
            $trade->other_hkd = $params['other_hkd'];
            $trade->total_cost_rmb = $params['total_cost_rmb'];
            $trade->agent_id = $params['agent_id'];
            $trade->status = PayableTradeModel::STATUS_UNPAID;
            $trade->pay_amount = 0;
            $trade->remarks = $params['remarks'] ?? '';
            $trade->created_admin_id = $request->get('auth')->id;
            $trade->save();

            return $this->success($trade);
        } catch (\Exception $e) {
            return $this->error('添加失败：' . $e->getMessage());
        }
    }

    /**
     * 更新一般贸易记录
     */
    public function update(Request $request, $id)
    {
        $trade = PayableTradeModel::find($id);
        if (!$trade) {
            return $this->error('一般贸易记录不存在');
        }

        $params = $request->all();
        $validator = Validator::make($params, [
            'date' => 'required|date',
            'mode' => 'required|string',
            'plate_number' => 'required|string',
            'tonnage' => 'required|numeric|min:0',
            'loading_location' => 'required|string',
            'customs_location' => 'required|string',
            'unloading_location' => 'required|string',
            'freight_rmb' => 'required|numeric|min:0',
            'mainland_addition_rmb' => 'required|numeric|min:0',
            'overtime_rmb' => 'required|numeric|min:0',
            'no_wait_rmb' => 'required|numeric|min:0',
            'parking_fee_rmb' => 'required|numeric|min:0',
            'weighing_fee_rmb' => 'required|numeric|min:0',
            'registration_fee_hkd' => 'required|numeric|min:0',
            'parking_fee_hkd' => 'required|numeric|min:0',
            'other_hkd' => 'required|numeric|min:0',
            'total_cost_rmb' => 'required|numeric|min:0',
            'agent_id' => 'required|integer|min:1',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        try {
            $trade->date = $params['date'];
            $trade->mode = $params['mode'];
            $trade->plate_number = $params['plate_number'];
            $trade->tonnage = $params['tonnage'];
            $trade->loading_location = $params['loading_location'];
            $trade->customs_location = $params['customs_location'];
            $trade->unloading_location = $params['unloading_location'];
            $trade->freight_rmb = $params['freight_rmb'];
            $trade->mainland_addition_rmb = $params['mainland_addition_rmb'];
            $trade->overtime_rmb = $params['overtime_rmb'];
            $trade->no_wait_rmb = $params['no_wait_rmb'];
            $trade->parking_fee_rmb = $params['parking_fee_rmb'];
            $trade->weighing_fee_rmb = $params['weighing_fee_rmb'];
            $trade->registration_fee_hkd = $params['registration_fee_hkd'];
            $trade->parking_fee_hkd = $params['parking_fee_hkd'];
            $trade->other_hkd = $params['other_hkd'];
            $trade->total_cost_rmb = $params['total_cost_rmb'];
            $trade->agent_id = $params['agent_id'];
            $trade->remarks = $params['remarks'] ?? '';
            $trade->save();

            return $this->success($trade);
        } catch (\Exception $e) {
            return $this->error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 删除一般贸易记录
     */
    public function delete($id)
    {
        $trade = PayableTradeModel::find($id);
        if (!$trade) {
            return $this->error('一般贸易记录不存在');
        }

        if ($trade->status != PayableTradeModel::STATUS_UNPAID) {
            return $this->error('已付款的记录不能删除');
        }

        try {
            $trade->delete();
            return $this->success(true);
        } catch (\Exception $e) {
            return $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 获取一般贸易详情
     */
    public function detail($id)
    {
        $trade = PayableTradeModel::with(['createAdmin'])->find($id);
        if (!$trade) {
            return $this->error('一般贸易记录不存在');
        }

        return $this->success($trade);
    }

    /**
     * 设置付款状态
     */
    public function setPaid(Request $request, $id)
    {
        $trade = PayableTradeModel::find($id);
        if (!$trade) {
            return $this->error('一般贸易记录不存在');
        }

        $validator = Validator::make($request->all(), [
            'pay_amount' => 'required|numeric|min:0',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $payAmount = $request->input('pay_amount');
        $totalAmount = $trade->total_cost_rmb;

        // 设置付款状态
        if ($payAmount >= $totalAmount) {
            $status = PayableTradeModel::STATUS_PAID;
            $payAmount = $totalAmount; // 确保支付金额不超过总金额
        } elseif ($payAmount > 0) {
            $status = PayableTradeModel::STATUS_PART_PAID;
        } else {
            $status = PayableTradeModel::STATUS_UNPAID;
        }

        try {
            $trade->pay_amount = $payAmount;
            $trade->status = $status;
            $trade->save();

            return $this->success($trade);
        } catch (\Exception $e) {
            return $this->error('设置付款状态失败：' . $e->getMessage());
        }
    }
} 